package cj.web.sc.controllers;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.ReturnUUID;
import cj.web.cc.controllers.BaseController;
import cj.web.cc.dao.ApplyDAO;
import cj.web.cc.dao.MemberDAO;
import cj.web.constants.SCOrderStatusEnum;
import cj.web.constants.WXPayAttachEnum;
import cj.web.game.dao.GameDAO;
import cj.web.pay.weixin.UnifiedOrder;
import cj.web.sc.dao.GoodsDAO;
import cj.web.sc.dao.OrderDAO;
import cj.web.sc.dao.SCCrowdFundOrderDAO;

@Path("order")
public class OrderController extends BaseController{
	@Autowired
	private GoodsDAO goodsDao;
	@Autowired
	private OrderDAO orderDao;
	@Autowired
	private MemberDAO memberDAO;
	@Autowired
	private GameDAO gameDao;
	@Autowired
	private SCCrowdFundOrderDAO scCrowdFundOrderDao;
	@Autowired
	private ApplyDAO applyDao;
	
	@Get("orderConfirm") //确认订单
	public String orderConfirm(Model model, @Param("goodsItemIds")String goodsItemIds, 
			@Param("counts")String counts, @Param("addressId")String addressId,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("logisticsPrice", LOGISTICS_FEE);
		if( isLogin(request) ){
			int buyerId = getBuyerId(request);
			model.add("buyerId", buyerId);
			
			//地址初始化
			if( addressId != null && addressId.length() > 0 ){
				List<Map> address = memberDAO.getAddressById(addressId);
				if(address != null && address.size() > 0){
					model.add("Address", address.get(0));
				}
			}
			else{
				List<Map> address = memberDAO.getFirstAddress(buyerId);
				if(address != null && address.size() > 0){
					model.add("Address", address.get(0));
				}
			}
			
			//商品初始化
			if(goodsItemIds != null && goodsItemIds.length() > 0 && 
					counts != null && counts.length() > 0){
				String[] itemIds = goodsItemIds.split(",");
				String[] itemCnts = counts.split(",");
				List<Map> objs = new ArrayList<Map>();
				if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
						itemCnts.length > 0 && itemIds.length == itemCnts.length){
					for(int i = 0; i < itemIds.length; i++){
						int itemId = Integer.parseInt(itemIds[i]);
						int count = Integer.parseInt(itemCnts[i]);
						List<Map> goodsItem = goodsDao.getGoodsItemById(itemId);
						if(goodsItem != null && goodsItem.size() > 0){
							Map obj = goodsItem.get(0);
							int inventory = Integer.parseInt(obj.get("inventory").toString());  //验证库存
							if(inventory < count){
								String goodsName = obj.get("name").toString();
								model.add("warning", goodsName + "库存不足");
								return "/views/mall/orderNothing.vm";
							}
							obj.put("propValueNames", obj.get("propValueNames").toString().replaceAll(",", ""));
							obj.put("count", itemCnts[i]);
							//加上 categoryId 
							model.add("categoryId",obj.get("categoryId").toString());
							objs.add(obj);
						}
						else{
							model.add("warning", "该商品已下架");
							return "/views/mall/orderNothing.vm";
						}
					}
				}
				else{
					model.add("warning", "该商品已下架");
					return "/views/mall/orderNothing.vm";
				}
				model.add("Objs",objs);
			
				if(objs.size() > 0){
					int sellerId = Integer.parseInt(objs.get(0).get("sellerId").toString());
					String sellerName = goodsDao.getSellerName(sellerId);
					model.add("sellerId",sellerId);
					model.add("sellerName",sellerName);
				}
			}
			else{
				model.add("warning", "该商品已下架");
				return "/views/mall/orderNothing.vm";
			}
			
			model.add("goodsItemIds",goodsItemIds);
			model.add("counts",counts);
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			return "/views/mall/orderConfirm.vm";
		}
		else{
			String retPg = "/order/orderConfirm?goodsItemIds=" + goodsItemIds + "&counts=" + counts;
			setCookie(response, "returnPage", retPg);//订单
			return "r:../user/loginPage";
		}
	}
	
	@Get("orderZCConfirm") //众筹确认订单
	public String orderZCConfirm(Model model, @Param("goodsItemIds")String goodsItemIds, 
			@Param("counts")String counts, @Param("addressId")String addressId,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("logisticsPrice", 0);//众筹的书  不要运费
		if( isLogin(request) ){
			int buyerId = getBuyerId(request);
			model.add("buyerId", buyerId);
			
			//地址初始化
			if( addressId != null && addressId.length() > 0 ){
				List<Map> address = memberDAO.getAddressById(addressId);
				if(address != null && address.size() > 0){
					model.add("Address", address.get(0));
				}
			}
			else{
				List<Map> address = memberDAO.getFirstAddress(buyerId);
				if(address != null && address.size() > 0){
					model.add("Address", address.get(0));
				}
			}
			
			//商品初始化
			if(goodsItemIds != null && goodsItemIds.length() > 0 && 
					counts != null && counts.length() > 0){
				String[] itemIds = goodsItemIds.split(",");
				String[] itemCnts = counts.split(",");
				List<Map> objs = new ArrayList<Map>();
				if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
						itemCnts.length > 0 && itemIds.length == itemCnts.length){
					for(int i = 0; i < itemIds.length; i++){
						int itemId = Integer.parseInt(itemIds[i]);
						int count = Integer.parseInt(itemCnts[i]);
						List<Map> goodsItem = goodsDao.getGoodsItemById(itemId);
						if(goodsItem != null && goodsItem.size() > 0){
							Map obj = goodsItem.get(0);
							int inventory = Integer.parseInt(obj.get("inventory").toString());  //验证库存
							if(inventory < count){
								String goodsName = obj.get("name").toString();
								model.add("warning", goodsName + "库存不足");
								return "/views/mall/orderNothing.vm";
							}
							obj.put("propValueNames", obj.get("propValueNames").toString().replaceAll(",", ""));
							obj.put("count", itemCnts[i]);
							//加上 categoryId 
							model.add("categoryId",obj.get("categoryId").toString());
							objs.add(obj);
						}
						else{
							model.add("warning", "该商品已下架");
							return "/views/mall/orderNothing.vm";
						}
					}
				}
				else{
					model.add("warning", "该商品已下架");
					return "/views/mall/orderNothing.vm";
				}
				model.add("Objs",objs);
			
				if(objs.size() > 0){
					int sellerId = Integer.parseInt(objs.get(0).get("sellerId").toString());
					String sellerName = goodsDao.getSellerName(sellerId);
					model.add("sellerId",sellerId);
					model.add("sellerName",sellerName);
				}
			}
			else{
				model.add("warning", "该商品已下架");
				return "/views/mall/orderNothing.vm";
			}
			
			model.add("goodsItemIds",goodsItemIds);
			model.add("counts",counts);
			
			//活动列表
			List<Map> gamels = gameDao.queryAll();
			model.add("gamels",gamels);
			
			model.add("urlGameId",getCookieValueByName(request, "urlGameId"));
			model.add("urlCode",getCookieValueByName(request, "urlCode"));
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			return "/views/mall/orderZCConfirm.vm";
		}
		else{
			String retPg = "/order/orderZCConfirm?goodsItemIds=" + goodsItemIds + "&counts=" + counts;
			setCookie(response, "returnPage", retPg);//订单
			return "r:../user/loginPage";
		}
	}
	
	@Get("cart") //购物车
	public String cart(Model model, HttpServletRequest request,HttpServletResponse response){
		if( isLogin(request) ){
			int buyerId = getBuyerId(request);
			List<Map> Objs = orderDao.cartByBuyerId(buyerId);
			if(Objs != null && Objs.size() > 0){
				model.add("Objs", Objs);
			}
			else{
				model.add("warning", "购物车空空如也~");
				return "/views/mall/orderNothing.vm";
			}
			
		}
		else{
			setCookie(response, "returnPage", "/order/cart");//订单
			return "r:../user/loginPage";
		}
		
		return "/views/mall/cart.vm";
	}
	
	@Get("emptyCart")
	public String emptyCart(Model model){
		model.add("warning", "购物车空空如也~");
		return "/views/mall/orderNothing.vm";
	}
	
	@Post("delCart")
	public String delCart(@Param("ids")String ids){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		JSONArray joIds = JSONArray.fromObject(ids);
		List<Integer> arrIds = new ArrayList<Integer>();
		for(int i = 0; i < joIds.size(); i++){
			arrIds.add(joIds.getInt(i));
		}
		orderDao.delCartByIds(arrIds);
		
		return "@" + jo.toString();
	}
	
	@Post("cartCnt")
	public String cartCnt(HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		int cartCnt = 0;
		if(isLogin(request)){
			int buyerId = getBuyerId(request);
			cartCnt = orderDao.getCartCntByBuyerId(buyerId);
		}
		
		jo.put("cartCnt", cartCnt);
		return "@" + jo.toString();
	}
	
	@Post("settleAccounts")
	public String settleAccounts(@Param("sellerId")int sellerId, @Param("buyerId")int buyerId,  
			@Param("addressId")String addressId, @Param("isInvoice")int isInvoice, @Param("invoiceHead")String invoiceHead,
			@Param("memo")String memo, @Param("goodsItemIds")String goodsItemIds, @Param("counts")String counts, @Param("cartIds")String cartIds,
			HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		BigDecimal priceForPay = new BigDecimal(0);
		//验证库存
		if(goodsItemIds != null && goodsItemIds.length() > 0 && 
				counts != null && counts.length() > 0){
			String[] itemIds = goodsItemIds.split(",");
			String[] itemCnts = counts.split(",");
			if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
					itemCnts.length > 0 && itemIds.length == itemCnts.length){
				for(int i = 0; i < itemIds.length; i++){
					int goodsItemId = Integer.parseInt(itemIds[i]);
					int count =  Integer.parseInt(itemCnts[i]);
					
					List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
					if(goodsItem != null && goodsItem.size() > 0){
						Map obj = goodsItem.get(0);
						int inventory = Integer.parseInt(obj.get("inventory").toString());  //验证库存
						if(inventory < count){
							jo.put("goodsName", obj.get("name").toString() + "库存不足");
							jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
							return "@" + jo.toString();
						}
						
						String itemPrice = obj.get("discntPrice").toString();
						BigDecimal itemsTotal = new BigDecimal(itemPrice).multiply(new BigDecimal(count));
						priceForPay = priceForPay.add(itemsTotal);   //计算订单总价
					}
					else{
						jo.put("goodsName", "该商品已下架");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
					
				}
			}
			else{
				jo.put("goodsName", "该商品已下架");
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				return "@" + jo.toString();
			}
		}
		else{
			jo.put("goodsName", "该商品已下架");
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
		String phone = memberDAO.getPhoneById(buyerId);
		String receiverName = "";
		String receiverPhone = "";
		String receiverAddress = "";
		List<Map> address = memberDAO.getAddressById(addressId);
		if(address != null && address.size() > 0){
			receiverName = address.get(0).get("receiverName").toString();
			receiverPhone = address.get(0).get("receiverPhone").toString();
			String province = address.get(0).get("province").toString();
			String city = address.get(0).get("city").toString();
			String area = address.get(0).get("area").toString();
			String addr = address.get(0).get("address").toString();
			
			if( city.indexOf(province) > -1 ){
				receiverAddress = city + area + addr;
			}
			else{
				receiverAddress = province + city + area + addr;
			}
		}
		int status = SCOrderStatusEnum.prepay.getValue();
		String orderNo = ReturnUUID.getOrderNo(ReturnUUID.getRandomNum());
		
		priceForPay = priceForPay.add(new BigDecimal(LOGISTICS_FEE));//订单总价 + 运费
		String discntPrice = priceFormat(priceForPay.doubleValue()); //订单价
		int orderId = orderDao.createOrder(buyerId,sellerId,orderNo,discntPrice,receiverName,receiverPhone,receiverAddress,
				isInvoice,invoiceHead,memo,status,phone);
		
		//生成订单详情
		if(goodsItemIds != null && goodsItemIds.length() > 0 && 
				counts != null && counts.length() > 0){
			String[] itemIds = goodsItemIds.split(",");
			String[] itemCnts = counts.split(",");
			if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
					itemCnts.length > 0 && itemIds.length == itemCnts.length){
				for(int i = 0; i < itemIds.length; i++){
					int goodsItemId = Integer.parseInt(itemIds[i]);
					int count =  Integer.parseInt(itemCnts[i]);
					orderDao.createOrderItem(orderId,goodsItemId,count,phone);
				}
			}
		}
		
		//如果是从购物车生成订单，删除购物车
		if( cartIds != null && cartIds.length() > 0 ){
			String[] arrCartIds = cartIds.split(",");
			if( arrCartIds!= null && arrCartIds.length > 0){
				List<Integer> arrIds = new ArrayList<Integer>();
				for(int i = 0; i < arrCartIds.length; i++){
					arrIds.add(Integer.valueOf(arrCartIds[i]));
				}
				orderDao.delCartByIds(arrIds);
			}
		}
		
		//调用微信接口
		String total_fee = priceFormat(priceForPay.multiply(new BigDecimal(100)).doubleValue()); //订单价 × 100
		String spbill_create_ip = request.getRemoteAddr();
		String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
        String openId = getCookieValueByName(request, "openId");
        if(openId != null && openId.length() > 0){
        	UnifiedOrder unifiedOrder = new UnifiedOrder();
    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的订单", orderNo, total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.SC.getValue());
    		jo.put("rtn", prepay);
        }
        else{
        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
        }
		
		return "@" + jo.toString();
	}
	
	/**
	 * 众筹出书
	 * @param sellerId
	 * @param buyerId
	 * @param addressId
	 * @param isInvoice
	 * @param invoiceHead
	 * @param memo
	 * @param goodsItemIds
	 * @param counts
	 * @param cartIds
	 * @param gameId	活动ID
	 * @param code		参赛证号
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Post("settleZCAccounts")
	public String settleZCAccounts(@Param("sellerId")int sellerId, @Param("buyerId")int buyerId,  
			@Param("addressId")String addressId, @Param("isInvoice")int isInvoice, @Param("invoiceHead")String invoiceHead,
			@Param("memo")String memo, @Param("goodsItemIds")String goodsItemIds, @Param("counts")String counts, 
			@Param("cartIds")String cartIds,@Param("gameId")int gameId,@Param("code")String code,
			HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String openId = getCookieValueByName(request, "openId");
        if(openId == null || openId.length() <= 0){
        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
        	jo.put("returnCode", Constants.returnObj.returnCode.code_7); //不在微信中
        	return "@" + jo.toString();
        }
		
		BigDecimal priceForPay = new BigDecimal(0);
		
		//活动信息
		List<Map> replis = applyDao.queryByGameIdAndCode(gameId, code);
		if(replis==null || replis.size()==0){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_5); //不存在
			return "@" + jo.toString();
		}
		
		String level = replis.get(0).get("level")==null?"":replis.get(0).get("level").toString();
		if("".equals(level)){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_6); //无获奖信息
			return "@" + jo.toString();
		}
		
		//验证库存
		if(goodsItemIds != null && goodsItemIds.length() > 0 && 
				counts != null && counts.length() > 0){
			String[] itemIds = goodsItemIds.split(",");
			String[] itemCnts = counts.split(",");
			if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
					itemCnts.length > 0 && itemIds.length == itemCnts.length){
				for(int i = 0; i < itemIds.length; i++){
					int goodsItemId = Integer.parseInt(itemIds[i]);
					int count =  Integer.parseInt(itemCnts[i]);
					
					List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
					if(goodsItem != null && goodsItem.size() > 0){
						Map obj = goodsItem.get(0);
						int inventory = Integer.parseInt(obj.get("inventory").toString());  //验证库存
						if(inventory < count){
							jo.put("goodsName", obj.get("name").toString() + "库存不足");
							jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
							return "@" + jo.toString();
						}
						
						String itemPrice = obj.get("discntPrice").toString();
						BigDecimal itemsTotal = new BigDecimal(itemPrice).multiply(new BigDecimal(count));
						priceForPay = priceForPay.add(itemsTotal);   //计算订单总价
					}
					else{
						jo.put("goodsName", "该商品已下架");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
					
				}
			}
			else{
				jo.put("goodsName", "该商品已下架");
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				return "@" + jo.toString();
			}
		}
		else{
			jo.put("goodsName", "该商品已下架");
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
		String phone = memberDAO.getPhoneById(buyerId);
		String receiverName = "";
		String receiverPhone = "";
		String receiverAddress = "";
		List<Map> address = memberDAO.getAddressById(addressId);
		if(address != null && address.size() > 0){
			receiverName = address.get(0).get("receiverName").toString();
			receiverPhone = address.get(0).get("receiverPhone").toString();
			String province = address.get(0).get("province").toString();
			String city = address.get(0).get("city").toString();
			String area = address.get(0).get("area").toString();
			String addr = address.get(0).get("address").toString();
			
			if( city.indexOf(province) > -1 ){
				receiverAddress = city + area + addr;
			}
			else{
				receiverAddress = province + city + area + addr;
			}
		}
		int status = SCOrderStatusEnum.prepay.getValue();
		String orderNo = ReturnUUID.getOrderNo(ReturnUUID.getRandomNum());
		
		priceForPay = priceForPay.add(new BigDecimal(0));//订单总价 + 运费
		String discntPrice = priceFormat(priceForPay.doubleValue()); //订单价
		int orderId = scCrowdFundOrderDao.createOrder(buyerId,sellerId,orderNo,discntPrice,receiverName,receiverPhone,receiverAddress,
				isInvoice,invoiceHead,memo,status,phone,gameId,code,PROGRESS);
		
		//生成订单详情
		if(goodsItemIds != null && goodsItemIds.length() > 0 && 
				counts != null && counts.length() > 0){
			String[] itemIds = goodsItemIds.split(",");
			String[] itemCnts = counts.split(",");
			if(itemIds != null && itemIds.length > 0 && itemCnts != null && 
					itemCnts.length > 0 && itemIds.length == itemCnts.length){
				for(int i = 0; i < itemIds.length; i++){
					int goodsItemId = Integer.parseInt(itemIds[i]);
					int count =  Integer.parseInt(itemCnts[i]);
					scCrowdFundOrderDao.createOrderItem(orderId,goodsItemId,count,phone);
				}
			}
		}
		
		//如果是从购物车生成订单，删除购物车
		if( cartIds != null && cartIds.length() > 0 ){
			String[] arrCartIds = cartIds.split(",");
			if( arrCartIds!= null && arrCartIds.length > 0){
				List<Integer> arrIds = new ArrayList<Integer>();
				for(int i = 0; i < arrCartIds.length; i++){
					arrIds.add(Integer.valueOf(arrCartIds[i]));
				}
				orderDao.delCartByIds(arrIds);
			}
		}
		
		//调用微信接口
		String total_fee = priceFormat(priceForPay.multiply(new BigDecimal(100)).doubleValue()); //订单价 × 100
		String spbill_create_ip = request.getRemoteAddr();
		String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
        if(openId != null && openId.length() > 0){
        	UnifiedOrder unifiedOrder = new UnifiedOrder();
    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的订单", orderNo, total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.ZC.getValue());
    		jo.put("rtn", prepay);
        }
        else{
        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
        	jo.put("returnCode", Constants.returnObj.returnCode.code_7); //不在微信中
        }
		
		return "@" + jo.toString();
	}
	
	private String priceFormat(double price){
		DecimalFormat df = new DecimalFormat("#.##");
		return df.format(price);
	}
	
	@Post("pay")
	public String pay(@Param("id")int orderId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> orderObj = orderDao.getOrderById(orderId);
		
		if(orderObj != null && orderObj.size() > 0){
			Map obj = orderObj.get(0);
			
			int status = Integer.parseInt(obj.get("status").toString());
			if( status != SCOrderStatusEnum.prepay.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //该订单已付款或失效
				return "@" + jo.toString();
			}
			
			//验证商品 及 库存
			List<Map> orderItems = orderDao.getItemsByOrderId(orderId);
			for(Map orderItem : orderItems){
				String goodsName = orderItem.get("goodsItemName").toString();
				int goodsItemId = Integer.parseInt(orderItem.get("goodsItemId").toString());
				int count = Integer.parseInt(orderItem.get("count").toString());
				
				List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
				if(goodsItem != null && goodsItem.size() > 0){
					Map goods = goodsItem.get(0);
					int inventory = Integer.parseInt(goods.get("inventory").toString());
					if( inventory < count ){
						jo.put("goodsName", goodsName + "库存不足");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
					
					int goodsId = Integer.parseInt(goods.get("goodsId").toString());
					List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
					if(goodsObj == null){
						jo.put("goodsName", goodsName + "已下架");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
				}
				else{
					jo.put("goodsName", goodsName + "已下架");
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@" + jo.toString();
				}
			}
			
			//调用微信接口
			BigDecimal priceBD = new BigDecimal(obj.get("discntPrice").toString());
			String total_fee = priceFormat(priceBD.multiply(new BigDecimal(100)).doubleValue()); //订单价 × 100
			String spbill_create_ip = request.getRemoteAddr();
			String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
	        String openId = getCookieValueByName(request, "openId");
	        if(openId != null && openId.length() > 0){
	        	UnifiedOrder unifiedOrder = new UnifiedOrder();
	    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的订单", obj.get("orderNo").toString(), total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.SC.getValue());
	    		jo.put("rtn", prepay);
	    		return "@" + jo.toString();
	        }
	        else{
	        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	        	return "@" + jo.toString();
	        }
		}
		else{
			jo.put("goodsName", "该订单已失效");
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
	}
	
	/**
	 * 众筹付款
	 * @param orderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Post("payZC")
	public String payZC(@Param("id")int orderId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> orderObj = scCrowdFundOrderDao.getOrderById(orderId);
		
		if(orderObj != null && orderObj.size() > 0){
			Map obj = orderObj.get(0);
			
			int status = Integer.parseInt(obj.get("status").toString());
			if( status != SCOrderStatusEnum.prepay.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //该订单已付款或失效
				return "@" + jo.toString();
			}
			
			//验证商品 及 库存
			List<Map> orderItems = scCrowdFundOrderDao.getItemsByOrderId(orderId);
			for(Map orderItem : orderItems){
				String goodsName = orderItem.get("goodsItemName").toString();
				int goodsItemId = Integer.parseInt(orderItem.get("goodsItemId").toString());
				int count = Integer.parseInt(orderItem.get("count").toString());
				
				List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
				if(goodsItem != null && goodsItem.size() > 0){
					Map goods = goodsItem.get(0);
					int inventory = Integer.parseInt(goods.get("inventory").toString());
					if( inventory < count ){
						jo.put("goodsName", goodsName + "库存不足");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
					
					int goodsId = Integer.parseInt(goods.get("goodsId").toString());
					List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
					if(goodsObj == null){
						jo.put("goodsName", goodsName + "已下架");
						jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
						return "@" + jo.toString();
					}
				}
				else{
					jo.put("goodsName", goodsName + "已下架");
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@" + jo.toString();
				}
			}
			
			//调用微信接口
			BigDecimal priceBD = new BigDecimal(obj.get("discntPrice").toString());
			String total_fee = priceFormat(priceBD.multiply(new BigDecimal(100)).doubleValue()); //订单价 × 100
			String spbill_create_ip = request.getRemoteAddr();
			String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
	        String openId = getCookieValueByName(request, "openId");
	        if(openId != null && openId.length() > 0){
	        	UnifiedOrder unifiedOrder = new UnifiedOrder();
	    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的订单", obj.get("orderNo").toString(), total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.ZC.getValue());
	    		jo.put("rtn", prepay);
	    		return "@" + jo.toString();
	        }
	        else{
	        	jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	        	return "@" + jo.toString();
	        }
		}
		else{
			jo.put("goodsName", "该订单已失效");
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
	}
	
	private int getBuyerId(HttpServletRequest request){
    	String phone = getCookieValueByName(request, "phone");
		int buyerId = memberDAO.getBuyerId(phone);
		
		return buyerId;
    }
	
}
